﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;

namespace SteveTPham.QueryAnything.DataSetTools
{
	public class Repetitive
	{
		private string fieldSeparator = " ";
		private string recordSeparator = "\r\n";

		#region Constructors
		public Repetitive()
		{
		}

		public Repetitive(string fieldSeparator, string recordSeparator)
		{
			this.fieldSeparator = fieldSeparator;
			this.recordSeparator = recordSeparator;
		}
		#endregion

		public string FieldSeparator
		{
			get
			{
				return fieldSeparator;
			}
			set
			{
				fieldSeparator = value;
			}
		}

		public string RecordSeparator
		{
			get
			{
				return recordSeparator;
			}
			set
			{
				recordSeparator = value;
			}
		}

		public string Convert(DataTable dt, string line)
		{
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < dt.Rows.Count; i++)
			{
				DataRow dr = dt.Rows[i];
				sb.Append(Convert(dr, line) + recordSeparator);
			}

			return sb.ToString();
		}

		public string Convert(DataRow dr, string line)
		{
			StringBuilder sb = new StringBuilder(line);
			MatchCollection mc = Regex.Matches(line, @"\${1,2}[^ ]+", RegexOptions.None);

			for (int i = 0; i < mc.Count; i++)
			{
				Match m = mc[i];
				string var = line.Substring(m.Index, m.Length);
				string value = string.Empty;

				if (var.StartsWith("$$"))
					continue;

				int idx = -1;

				if (int.TryParse(var.Substring(1), out idx))
				{
					value = Arg(dr, idx);
				}
				else
				{
					value = Arg(dr, var.Substring(1));
				}

				sb.Replace(var, value);
			}
			return sb.ToString();
		}

		private string Arg(DataRow dr, string columnName)
		{
			return dr[columnName].ToString();
		}

		private string Arg(DataRow dr, int columnIndex)
		{
			StringBuilder sb = new StringBuilder();

			if (columnIndex == 0)
			{
				for (int i = 0; i < dr.Table.Columns.Count; i++)
				{
					if (sb.Length > 0)
						sb.Append(fieldSeparator);
					sb.Append(dr[i]);
				}
			}
			else
			{
				sb.Append(dr[columnIndex - 1]);
			}

			return sb.ToString();
		}
	}
}
